package com.wfh.picture.controller;

import com.wfh.picture.annotation.AuthCheck;
import com.wfh.picture.common.BaseResponse;
import com.wfh.picture.common.ResultUtils;
import com.wfh.picture.constant.UserConstant;
import com.wfh.picture.exception.BusinessException;
import com.wfh.picture.exception.ErrorCode;
import com.wfh.picture.manager.ObsManager;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @Author FengHuan Wang
 * @Date 2025/5/9 13:02
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private ObsManager obsManager;


    /**
     * 上传文件
     * @param multipartFile
     * @return
     */
    @ApiOperation("上传文件")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file")MultipartFile multipartFile){
        String filename = multipartFile.getOriginalFilename();
        String filePath = String.format("picture_test/%s", filename);
        File file = null;
        try {
            file = File.createTempFile(filePath, null);
            multipartFile.transferTo(file);
            String upload = obsManager.upload(file, filePath);
            return ResultUtils.success(upload);
        } catch (IOException e) {
            log.error("文件{}上传失败：{}", filePath, e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");
        }finally {
            if (file != null){
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete){
                    log.error("删除临时文件{}失败", filePath);
                }
            }
        }
    }

    /**
     * 下载文件
     * @param filePath
     * @param response
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/download")
    @ApiOperation("下载文件")
    public void downLoad(String filePath, HttpServletResponse response){
        try {
            String downLoad = obsManager.downLoad(filePath);
            byte[] bytes = downLoad.getBytes();
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filePath);
            // 写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
